#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2022/1/18 15:26
    Desc  :
--------------------------------------
"""
from django.db import transaction
from django_http_log.common.request import BaseAPIView
from django_http_log.common.response import SuccessResponse, SystemExceptionResponse, CommonResponse

from common.decorator.token_decorator import Authentication
from common.enums.response_enums import CommonResultEnums
from common.utils.log_utils import logger
from common.utils.other_utils import get_time
from common.utils.token_utils import RequestAuthTokenUtil
from person.models import CaseModule
from person.serializers.module import CaseModuleSerializer, CaseModuleArraySerializer
from platform_auth.settings import APIDOC_DECORATOR


class CaseModuleBaseAPIView(BaseAPIView):
    Model = CaseModule

    serializer_class = CaseModuleSerializer


class CaseModuleAddAPIView(CaseModuleBaseAPIView):
    """用例模块添加"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/module/add', summary = '用例模块新增')
    @APIDOC_DECORATOR.ApiParams(value = 'parent', type = 'int', desc = '模块Id')
    @APIDOC_DECORATOR.ApiParams(value = 'name', type = 'string', require = True, desc = '模块名称')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):
        try:
            body: dict = request.data.copy()

            project = RequestAuthTokenUtil(request = request).get_project()
            userId, userName = RequestAuthTokenUtil(request = request).get_user_id_and_username()
            parent = body.get('parent')
            # 1. 根据ProjectId判断项目是否存在
            queryset_name = self.Model.objects.filter(name = body.get('name'), deleted = False, project = project)
            if queryset_name.count() != 0:
                return CommonResponse(codeEnums = CommonResultEnums.CASE_MODULE_NAME_IS_EXIST)
            # 1.1 判断parent是否存在
            if parent and parent != '':
                queryset_parent = self.Model.objects.filter(id = int(parent), deleted = False, project = project)
                if queryset_parent.count() == 0:
                    return CommonResponse(codeEnums = CommonResultEnums.CASE_MODULE_PARENT_ID_NOT_EXIST)
                else:
                    parent = queryset_parent.first().id
            else:
                parent = None
            # 2. 更新
            with transaction.atomic():
                module = self.Model.objects.create(
                    name = body.get('name'),
                    parent = parent,
                    project = project,
                    creatorName = userName,
                    creatorId = userId
                )
            # 3. 序列化
            serializer = self.serializer_class(module, exclude = self.exclude_fields)

            return SuccessResponse(result = serializer.data)

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseModuleListAPIView(CaseModuleBaseAPIView):
    """用例模块列表"""

    def post(self, request, *args, **kwargs):
        pass


class CaseModuleEditAPIView(CaseModuleBaseAPIView):
    """用例模块编辑"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/module/edit', summary = '用例模块编辑')
    @APIDOC_DECORATOR.ApiParams(value = 'parent', type = 'int', desc = '模块Id')
    @APIDOC_DECORATOR.ApiParams(value = 'name', type = 'string', require = True, desc = '模块名称')
    @APIDOC_DECORATOR.ApiParams(value = 'id', type = 'int', require = True, desc = '模块Id')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):
        try:
            body: dict = request.data.copy()

            project = RequestAuthTokenUtil(request = request).get_project()
            userId, userName = RequestAuthTokenUtil(request = request).get_user_id_and_username()
            parent = body.get('parent')
            queryset_id = self.Model.objects.filter(id = body.get('id'), deleted = False, project = project)
            if queryset_id.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.CASE_MODULE_ID_IS_NOT_EXIST)
            # 1. 根据ProjectId判断项目是否存在
            queryset_name = self.Model.objects.filter( name = body.get('name'), deleted = False,
                                                      project = project).exclude(id = body.get('id'))
            if queryset_name.count() != 0:
                return CommonResponse(codeEnums = CommonResultEnums.CASE_MODULE_NAME_IS_EXIST)
            # 1.1 判断parent是否存在
            if parent and parent != '':
                queryset_parent = self.Model.objects.filter(id = int(parent), deleted = False, project = project)
                if queryset_parent.count() == 0:
                    return CommonResponse(codeEnums = CommonResultEnums.CASE_MODULE_PARENT_ID_NOT_EXIST)
                else:
                    parent = queryset_parent.first().id
            else:
                parent = None

            with transaction.atomic():
                queryset_id.update(
                    name = body.get('name'),
                    parent = parent,
                    project = project,
                    updaterId = userId,
                    updaterName = userName,
                    updateTime = get_time(),
                )

            return SuccessResponse()

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseModuleDeleteAPIView(CaseModuleBaseAPIView):
    """用例模块删除"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/module/delete', summary = '用例模块删除')
    @APIDOC_DECORATOR.ApiParams(value = 'id', type = 'int', require = True, desc = '模块Id')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):
        try:
            body: dict = request.data.copy()

            project = RequestAuthTokenUtil(request = request).get_project()
            userId, userName = RequestAuthTokenUtil(request = request).get_user_id_and_username()

            # 1. 根据ProjectId判断项目是否存在
            queryset_id = self.Model.objects.filter(id = body.get('id'), deleted = False, project = project)
            if queryset_id.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.CASE_MODULE_ID_IS_NOT_EXIST)
            # 2. 更新
            with transaction.atomic():
                queryset_id.update(
                    deleted = True,
                    deleteTime = get_time(),
                    updaterId = userId,
                    updaterName = userName,
                    updateTime = get_time(),
                )

            return SuccessResponse()

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseModuleTreeAPIView(CaseModuleBaseAPIView):
    """用例模块结构树"""

    serializer_class = CaseModuleArraySerializer

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/module/tree', summary = '用例模块树形接口')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):
        try:

            project = RequestAuthTokenUtil(request = request).get_project()

            queryset = self.Model.objects.filter(parent = None, deleted = False, project = project).order_by(
                'createTime')

            serializer = self.serializer_class(queryset, many = True, exclude = self.exclude_fields)

            return SuccessResponse(result = {'array': serializer.data})

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseModuleArrayAPIView(CaseModuleBaseAPIView):
    """用例模块列表"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/module/array', summary = '用例模块列表接口')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):
        try:

            project = RequestAuthTokenUtil(request = request).get_project()

            queryset = self.Model.objects.filter(deleted = False, project = project).order_by(
                'createTime')

            serializer = self.serializer_class(queryset, many = True, exclude = self.exclude_fields)

            return SuccessResponse(result = {'array': serializer.data})

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()